<template>
  <div class="app-container" v-loading="loading">
    <el-card>
      <div
        :style="{
          'max-height': reViewState == 0 && userType == 0 ? '750px' : '830px',
          'overflow-y': 'auto',
          'overflow-x': 'hidden',
        }"
        ref="scrollContainer"
      >
        <el-page-header
          @back="goBack"
          :content="`设备编号：${deviceCode}`"
          style="margin-bottom: 10px"
          v-if="showBack"
        >
        </el-page-header>
        <div v-else style="margin-bottom: 10px">设备编号：{{ deviceCode }}</div>
        <el-row>
          <el-col
            :span="8"
            v-for="(item, index) in stepInfo"
            :key="item.bigStep"
          >
            <el-card
              style="margin: 0 5px 10px 0px; background-color: #fdf2d6d1"
            >
              <div style="margin-bottom: 10px">{{ titleFn(item) }}</div>
              <el-steps
                :active="activeFn(index, item, minStep, bigStep)"
                finish-status="success"
              >
                <el-step
                  v-for="(name, index2) in stepObj[item.bigStep]"
                  :key="name"
                  :title="stepName[name]"
                  @click.native="
                    handleStepClick(index, index2, item, minStep, bigStep)
                  "
                >
                </el-step>
              </el-steps> </el-card
          ></el-col>
        </el-row>

        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="success" size="mini" @click="addRow()" plain
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              size="mini"
              @click="delRow"
              plain
              :disabled="multiple"
              >删除</el-button
            >
          </el-col>
        </el-row> -->
        <el-table
          ref="refTable"
          :data="FACAData"
          border
          max-height="600"
          @selection-change="handleSelectionChange"
        >
          <!-- <el-table-column type="selection" width="55" align="center" fixed /> -->
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="50"
          />
          <el-table-column label="原因" align="center" prop="question">
            <!-- <template slot-scope="scope">
              <el-input
                type="textarea"
                rows="2"
                placeholder="请输入"
                v-model="scope.row.question"
              ></el-input>
            </template> -->
          </el-table-column>
          <el-table-column label="对策" align="center" prop="answer">
            <!-- <template slot-scope="scope">
              <el-input
                type="textarea"
                rows="2"
                placeholder="请输入"
                v-model="scope.row.answer"
              ></el-input>
            </template> -->
          </el-table-column>
        </el-table>
        <el-form ref="form" :model="form" style="margin-top: 20px">
          <el-divider
            ><div
              style="
                display: flex;
                align-items: center;
                text-align: center;
                margin-bottom: 5px;
              "
            >
              <span style="font-size: 18px; font-weight: 700; color: #1890ff"
                >意见栏</span
              >
            </div></el-divider
          >
          <el-radio-group
            v-model="form.type"
            size="small"
            v-if="reViewState == 0 && userType == 0"
          >
            <el-radio-button :label="0">特采</el-radio-button>
            <el-radio-button :label="1">报废</el-radio-button>
            <el-radio-button :label="2">其他</el-radio-button>
          </el-radio-group>
          <div v-show="form.type == 2">
            <el-table
              :data="approveData"
              border
              max-height="600"
              :row-class-name="tableRowClassName"
              style="margin-top: 10px"
            >
              <el-table-column
                label="步骤"
                align="center"
                prop="user"
                width="150"
              >
                <template slot-scope="scope">{{
                  stepName[scope.row.step]
                }}</template>
              </el-table-column>
              <el-table-column
                label="审批人"
                align="center"
                prop="user"
                width="150"
              />
              <el-table-column
                label="意见类型"
                align="center"
                prop="type"
                width="150"
              >
                <template slot-scope="scope">{{
                  scope.row.type == 0
                    ? "特采"
                    : scope.row.type == 1
                    ? "报废"
                    : "其他"
                }}</template>
              </el-table-column>
              <el-table-column label="意见" align="center" prop="msg">
                <template slot-scope="scope">
                  <el-input
                    type="textarea"
                    rows="2"
                    placeholder="请输入"
                    v-model="scope.row.msg"
                    v-if="!scope.row.disable"
                  ></el-input>
                  <span v-else>{{ scope.row.msg }}</span>
                </template>
              </el-table-column>
            </el-table>

            <!-- <el-divider
            ><div
              style="
                display: flex;
                align-items: center;
                text-align: center;
                margin-bottom: 5px;
              "
            >
              <span style="font-size: 18px; font-weight: 700; color: #1890ff"
                >文档</span
              >
            </div></el-divider
          > -->
            <el-row :gutter="10" class="mb8" style="margin-top: 15px">
              <el-col :span="1.5" v-if="reViewState == 0 && userType == 0">
                <el-upload
                  ref="upload"
                  action=""
                  multiple
                  :http-request="handleFileUpload"
                  :show-file-list="false"
                >
                  <el-button size="mini" type="primary" plain>上传</el-button>
                </el-upload>
              </el-col>
            </el-row>
            <el-table
              :data="form.reqFileList"
              style="width: 100%"
              border
              :stripe="true"
              id="reqFileList"
              :row-class-name="rowClassName"
            >
              <el-table-column
                type="index"
                label="序号"
                width="50"
                align="center"
              />
              <el-table-column align="center" label="步骤" prop="step">
                <template slot-scope="scope">{{
                  stepName[scope.row.step]
                }}</template></el-table-column
              >
              <el-table-column
                align="center"
                label="上传人"
                prop="user"
              ></el-table-column>
              <el-table-column
                align="center"
                label="文件名"
                prop="name"
              ></el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="165"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="success"
                    plain
                    @click="handleDownloadFile(scope.row)"
                    v-if="scope.row.disable"
                    >下载</el-button
                  >
                  <el-button
                    size="mini"
                    type="danger"
                    plain
                    @click="deleteFile(scope.row)"
                    v-else
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
    </el-card>
    <el-form
      ref="NextForm"
      :model="NextForm"
      :rules="NextFormRules"
      style="margin-top: 20px"
      v-if="reViewState == 0 && userType == 0"
    >
      <el-form-item
        prop="YesNo"
        style="margin-left: 20px"
        label="当前级别审批流程:"
      >
        <el-radio-group v-model="NextForm.YesNo" size="mini">
          <el-radio-button :label="0">通知本级下一审批人</el-radio-button>
          <el-radio-button :label="1">完了</el-radio-button>
        </el-radio-group>

        <el-button
          size="mini"
          type="success"
          plain
          style="margin-left: 25px"
          @click="dialogSubmit()"
          >提交</el-button
        ></el-form-item
      >
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { downloadFile } from "@/utils/newJs/fileFn.js";
import {
  reqGetApproveInfo,
  reqSendEMail,
  reqGetReViewSub,
  reqInsertReViewSub,
  reqGetMailInfo,
} from "@/api/newApi/OCAP/index.js";
export default {
  data() {
    return {
      loading: false,
      form: { reqFileList: [], type: "2" },
      rules: {},
      NextForm: { YesNo: 0 },
      NextFormRules: {
        YesNo: [{ required: true, message: "必填项", trigger: "blur" }],
      },
      FileList: [],
      defaultData: { id: null, question: null, answer: null },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      multiple2: true,
      //当前行id
      resultId: null,
      FACAData: [],
      selections2: [],
      //步骤
      active: 1,
      now: null, //当前步骤字段名
      bigStep: null,
      minStep: null,
      deviceCode: null,
      stepInfo: [
        {
          bigStep: 1,
          stepTotal: 3,
        },
        {
          bigStep: 2,
          stepTotal: 3,
        },
        {
          bigStep: 3,
          stepTotal: 2,
        },
      ],
      stepObj: {
        1: ["FACA1", "FACA2", "FACA3"],
        2: ["QC1", "QC2", "QC3"],
        3: ["QA1", "QA2"],
      },
      stepName: {
        FACA1: "FACA工程师",
        FACA2: "FACA课长",
        FACA3: "FACA部长",
        QC1: "QC工程师",
        QC2: "QC课长",
        QC3: "QC部长",
        QA1: "QA部长",
        QA2: "QA本部长",
      },
      approveData: [], //意见信息
      reViewState: null, //0：结束，1：未结束
      userType: null, //0：能提交，1：不能提交
      showBack: false,
    };
  },
  computed: {
    ...mapGetters(["account"]),
  },
  async mounted() {
    this.showBack = window.history.length > 1;
    //判断是否有返回
    this.resultId = this.$route.query.resultId;
    this.deviceCode = this.$route.query.deviceCode;
    this.getInfo();
    //滚动条
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  },
  methods: {
    scrollToBottom() {
      const container = this.$refs.scrollContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (!row.disable) {
        return "enabled-row";
      }
      return "";
    },
    handleStepClick(index1, index2, item, minStep, bigStep) {
      // if (index1 + 1 === Number(bigStep) && index2 + 1 <= Number(minStep)) {
      //   this.$modal.msgSuccess("OKKK");
      // } else {
      //   this.$modal.msgError("该步骤未完成");
      // }
    },
    //设备步骤信息
    titleFn(item) {
      const titles = {
        1: "一级审批",
        2: "二级审批",
        3: "三级审批",
      };
      return `${titles[item.bigStep]}`;
    },
    async getInfo() {
      const loading = this.$loading({
        lock: true,
        text: "加载中",
        spinner: "el-icon-loading",
      });
      let res = await reqGetReViewSub({
        userId: this.account,
        resultId: this.resultId.toString(),
      });
      if (res.code == 0) {
        this.reViewState = res.data.reViewState;
        this.userType = res.data.userType;
        //FACA信息
        this.FACAData = res.data.faca;
        this.now = res.data.now;
        //!动态更新stepObj和stepInfo
        let nowkey = null;
        for (const key in this.stepObj) {
          const index = this.stepObj[key].indexOf(this.now);
          if (index !== -1) {
            nowkey = key;
            break;
          }
        }
        //res.data.msg存在时，处理stepObj
        if (res.data.msg && res.data.msg.length > 0) {
          let newStepObj = {};
          for (const key in this.stepObj) {
            if (key == nowkey || key > nowkey) {
              newStepObj[key] = this.stepObj[key]; //保留stepObj中nowkey对应的整个数组
            } else {
              let resHasStep = []; //记录拥有的step
              res.data.msg.forEach((item) => {
                resHasStep.push(item.step);
              });
              //nowkey之前的：根据res.data.msg动态赋值
              for (let keyindex = nowkey; keyindex > 0; keyindex--) {
                let arr = [];
                this.stepObj[keyindex].forEach((item, index) => {
                  if (resHasStep.includes(item)) {
                    arr.push(item);
                  }
                });
                //!注意:每个设备到审批步骤时必定有“FACA工程师”数据，需要补上
                if (keyindex == 1) {
                  arr.unshift("FACA1");
                }
                newStepObj[keyindex] = arr;
              }
            }
          }
          //最终
          this.stepObj = newStepObj;
          this.stepInfo.forEach((item) => {
            item.stepTotal = this.stepObj[item.bigStep].length;
          });
          // console.log(this.stepInfo, "this.stepInfo");
        }
        //!
        //步骤条信息
        for (const key in this.stepObj) {
          const index = this.stepObj[key].indexOf(this.now);
          if (index !== -1) {
            this.bigStep = key;
            this.minStep = index + 1;
            break;
          }
        }
        //文件信息
        this.form.reqFileList = res.data.file ? res.data.file : [];
        if (this.form.reqFileList.length > 0) {
          this.form.reqFileList.forEach((item) => {
            item.disable = true;
          });
        }

        //意见信息
        this.approveData = res.data.msg ? res.data.msg : [];
        if (this.approveData.length > 0) {
          this.approveData.forEach((item) => {
            item.disable = true;
          });
        }
        //添加当前审批人的输入框
        if (this.reViewState == 0 && this.userType == 0) {
          this.approveData.push({
            step: this.now,
            user: this.account,
            disable: false,
          });
        }
      } else {
        this.$modal.msgError(res.msg);
      }
      loading.close();
    },
    activeFn(index, item, minStep, bigStep) {
      if (this.reViewState == 1) {
        return item.stepTotal;
      } else {
        if (index + 1 === Number(bigStep)) {
          return minStep - 1;
        } else if (index + 1 < Number(bigStep)) {
          return item.stepTotal;
        }
      }
    },
    goBack() {
      this.$router.push({
        name: "FACAApprove",
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id).sort((a, b) => b - a);
      this.single = selection.length != 1; // 非单个禁用
      this.multiple = !selection.length; // 非多个禁用
    },
    //添加行
    addRow() {
      this.FACAData.push({
        id: this.FACAData.length,
        question: "",
        answer: "",
      });

      //滚动条默认拉至表格最底下
      this.$nextTick(() => {
        let scrollHeight = this.$refs.refTable.bodyWrapper.scrollHeight;
        this.$refs.refTable.bodyWrapper.scrollTop = scrollHeight;
      });
    },
    //删除行
    delRow() {
      let Indexs = this.ids.map((item) => {
        return item + 1;
      });
      this.$modal
        .confirm(
          '是否确认删除序号为"' + Indexs.sort((a, b) => a - b) + '"的数据项？'
        )
        .then(() => {
          //删除
          this.FACAData = this.FACAData.filter((item, index) => {
            return !this.ids.includes(item.id);
          });
          //重新排序
          this.FACAData.forEach((item, index) => {
            item.id = index;
          });
          //重新赋值
          this.FACAData = [...this.FACAData];
        })
        .catch(() => {});
    },
    dialogSubmit() {
      this.$refs["NextForm"].validate(async (valid) => {
        if (valid) {
          let step = null; //判断下一步
          if (this.NextForm.YesNo == 0) {
            if (this.bigStep == 3) {
              if (this.minStep == 2) {
                step = "ok";
              } else {
                step = this.stepObj[this.bigStep][this.minStep];
              }
            } else {
              if (this.minStep < 3) {
                step = this.stepObj[this.bigStep][this.minStep];
              } else {
                step = this.stepObj[Number(this.bigStep) + 1][0];
              }
            }
          } else {
            if (this.bigStep == 3) {
              step = "ok";
            } else {
              step = this.stepObj[Number(this.bigStep) + 1][0];
            }
          }
          //意见
          let MsgInfo = this.approveData[this.approveData.length - 1].msg
            ? this.approveData[this.approveData.length - 1].msg
            : "";
          let msg = {
            ...this.approveData[this.approveData.length - 1],
            msg: this.form.type == "2" ? MsgInfo : "",
            type: Number(this.form.type),
          };

          let formData = new FormData();
          formData.set("userId", this.account);
          formData.set("resultId", this.resultId);
          formData.set("msg.step", msg.step);
          formData.set("msg.user", msg.user);
          formData.set("msg.msg", msg.msg);
          formData.set("msg.type", msg.type);
          formData.set("step", step);
          formData.set("now", this.now);
          this.FileList.forEach((file, index) => {
            formData.append(`fileContents`, file);
          });
          this.loading = true;
          let res1 = await reqInsertReViewSub(formData);
          if (res1.code == 0) {
            this.form.type = "2";
            this.NextForm.YesNo = 0;
            if (step != "ok") {
              let res2 = await reqSendEMail({
                deviceCode: this.deviceCode,
                resultId: this.resultId,
                NextStepName: step,
                NextStepNameZh: this.stepName[step],
              });
              if (res2.code == 200) {
                this.$modal.msgSuccess("提交成功,邮件已发送");
              } else {
                this.$modal.msgWarning(res2.msg);
              }
              this.loading = false;
              this.getInfo();
            } else {
              this.$modal.msgSuccess("提交成功");
              this.loading = false;
              this.getInfo();
            }
          } else {
            this.$modal.msgError(res1.msg);
          }
        }
      });
    },
    //#region **************** 文件方法 ************************
    //给row添加index属性
    rowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },
    // 删除文件
    deleteFile(row) {
      let numArr = [row.index + 1];
      let uidArr = [row.uid];
      this.$confirm(`确认删除序号为${numArr.toString()}的文件？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.form.reqFileList = this.form.reqFileList.filter(
            (item) => !item.uid || (item.uid && uidArr.indexOf(item.uid) == -1)
          );
          this.FileList = this.FileList.filter(
            (item) => !item.uid || (item.uid && uidArr.indexOf(item.uid) == -1)
          );
        })
        .catch(() => {});
    },
    // 上传文件
    async handleFileUpload(fileObject) {
      this.FileList.push(fileObject.file);
      this.form.reqFileList.push({
        disable: false,
        name: fileObject.file.name,
        step: this.now,
        user: this.account,
        url: "'",
        uid: fileObject.file.uid,
      });
    },
    async handleDownloadFile(row) {
      let flag = await downloadFile(row.url, row.name);
      if (flag == true) {
        this.$modal.msgSuccess("文件下载中...");
      } else {
        this.$modal.msgError(flag);
      }
    },
    //#endregion
  },
};
</script>
<style lang="scss" scoped>
//表头颜色
::v-deep .el-table .el-table__header-wrapper th,
.el-table .el-table__fixed-header-wrapper th {
  background-color: #f0f8ff !important;
}
//dialog
::v-deep .el-dialog__body {
  padding: 0 20px 10px 20px;
}
::v-deep .el-card__body {
  padding: 10px 10px 10px 10px;
}
//divider
::v-deep .el-divider {
  background-color: #1890ff;
  position: relative;
}

::v-deep .el-radio--mini.is-bordered .el-radio__label {
  font-size: 14px;
}
//意见栏当前行
::v-deep .enabled-row {
  background-color: #fdf4dd !important;
}
</style>